﻿<%@ WebHandler Language="C#" Class="EntrustMeteringVue3PageHandler" %>

/* Description:理化试验申请维护
 * Copyright (c) : 通力凯顿（北京）系统集成有限公司
 * Writer:zhunan 
 * create Date:2024.8.13
 */

using System;
using System.IO;
using System.Web;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using System.Collections.Generic;
using System.Data;
using System.Text;
using BusinessRule.DTO;
using DatabaseAccess.DBUtility;
using BusinessRule.Business;
using BusinessRule.IBusiness;
using BusinessRule.BusinessFactory;
using System.Net;
using System.Configuration;
using StackExchange.Redis;
using BusinessRule.Common;
using System.Linq;

public class EntrustMeteringVue3PageHandler : IHttpHandler, System.Web.SessionState.IRequiresSessionState
{
    CurrentUserInfo m_UserInfo = new CurrentUserInfo();
    uLMSEntrustIBusiness m_Entrust = uMESBusinessFactory.instance.GetuLMSEntrustMetering();
    uLMSCommonIBusiness m_Common = uMESBusinessFactory.instance.GetuLMSCommonObject();
    uLMSStepCheckPointIBusiness m_CheckPointObj = uMESBusinessFactory.instance.GetuLMSStepCheckPointObject();
    private bool isUseIP = Convert.ToBoolean(ConfigurationManager.AppSettings["IsUseIP"] == "1");
    public bool IsReusable { get { return false; } }
    public void ProcessRequest(HttpContext context)
    {
        string requestjson = "";
        using (System.IO.StreamReader reader = new StreamReader(context.Request.InputStream)) { requestjson = reader.ReadToEnd(); }
        JObject jObject = JsonConvert.DeserializeObject(requestjson) as JObject;
        if (jObject["type"] != null)
        {
            try
            {
                uMESProcessResult r = new uMESProcessResult();
                context.Response.ContentType = "text/json";
                string type = jObject["type"].ToString();
                switch (type)
                {
                    case "getEntrustMeteringNo":
                        r = getEntrustMeteringNo(jObject);//获取委托单号
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "getEntrustMeteringedQty":
                        r = getEntrustMeteringedQty(jObject);//获取批次当前序工序已经委托的数量
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "saveData":
                        r = saveData(jObject, context);//保存委托计量信息
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    default:
                        break;
                }
            }
            catch (Exception e)
            {
                uMESProcessResult r = new uMESProcessResult() { ReturnData = null, RowCount = "0", Code = "500", Message = e.Message };
                context.Response.ContentType = "text/json";
                context.Response.Write(JsonConvert.SerializeObject(r));
            }
        }
    }

    //获取委托单号
    uMESProcessResult getEntrustMeteringNo(JObject obj)
    {
        string EntrustMeteringNo = "WT-" + obj["employeename"] + "-" + DateTime.Now.ToString("yyMM");
        DataTable dt = m_Entrust.GetMaxEntrustName(EntrustMeteringNo);
        string strMax = dt.Rows[0]["ENTRUSTNAME"].ToString();
        if (strMax != "")
        {
            string strSequence = strMax.Substring(strMax.Length - 3);
            EntrustMeteringNo = EntrustMeteringNo + (Convert.ToInt32(strSequence) + 1).ToString("0000");
        }
        else
        {
            EntrustMeteringNo = EntrustMeteringNo + (Convert.ToInt32(1)).ToString("0000");
        }
        return new uMESProcessResult() { ReturnData = EntrustMeteringNo, RowCount = "0", Code = "200", Message = "请求成功" };
    }

    //获取批次当前序工序已经委托的数量
    uMESProcessResult getEntrustMeteringedQty(JObject obj)
    {
        string qty = "0";
        Dictionary<string, string> para = new Dictionary<string, string>();
        para.Add("ContainerID", obj["containerid"].ToString());
        para.Add("WorkflowStepID", obj["workflowstepid"].ToString());
        DataTable dt = m_Entrust.GetEntrustMeteringedQty(para);
        if (dt.Rows.Count > 0 && dt.Rows[0]["SUMQTY"].ToString() != "")
        {
            qty = dt.Rows[0]["SUMQTY"].ToString();
        }
        return new uMESProcessResult() { ReturnData = qty, RowCount = "0", Code = "200", Message = "请求成功" };
    }

    uMESProcessResult saveData(JObject obj, HttpContext context)
    {
        CurrentUserInfo m_UserInfo = m_Common.GetUserInfo(obj["employeename"].ToString(), "");
        EntrustMeteringDTO dto = new EntrustMeteringDTO();
        DataTable dtCheckItems = JsonConvert.DeserializeObject<DataTable>(obj["checkItemList"].ToString());
        dto.ContainerID = obj["containerid"].ToString();
        dto.WorkflowStepID = obj["workflowstepid"].ToString();
        dto.EntrustDate = Convert.ToDateTime(obj["requireGetDate"].ToString());//要求取件日期
        dto.ReserveDate = Convert.ToDateTime(obj["reserveGetDate"].ToString());//预计取件日期
        dto.EntrustMeasurementID = System.Guid.NewGuid().ToString();//唯一id
        dto.EntrustName = obj["entrustMeteringCheckName"].ToString();//委托单号
        dto.EntrustNote = obj["remark"].ToString();//委托备注
        dto.EntrustorID = m_UserInfo.EmployeeID;//委托人
        dto.EntrustQty = Convert.ToInt32(obj["entrustMeteringQty"].ToString());//委托数量
        dto.FactoryID = m_UserInfo.FactoryID;
        dto.ProductID = obj["productid"].ToString();
        dto.EntrusChecktype = Convert.ToInt32(obj["checktype"].ToString());//检验类型
        dto.IsPhy = 1;
        dto.BatchNO = obj["batchNO"].ToString();//炉批号
        dto.Specification = obj["specification"].ToString();//材料标准或规范
        bool isSaveSuccess = m_Entrust.AddEntrustMeteringInfo(dto);
        if (isSaveSuccess)
        {
            isSaveSuccess = AddEntrustMeteringDetail(dto.EntrustMeasurementID, dtCheckItems, obj["checktype"].ToString(), context);
        }
        return new uMESProcessResult() { ReturnData = isSaveSuccess, RowCount = "0", Code = "200", Message = "请求成功" };
    }

    private bool AddEntrustMeteringDetail(string EntrustMeasurementID, DataTable dtCheckItems, string checktype, HttpContext context)
    {
        EntrustMeteringDTO dto;
        string usingImg = ConfigurationManager.AppSettings["UsingCheckImageSavePath"];
        int seq = 1;
        DataTable dtImage = (DataTable)context.Session["dtImage"];
        foreach (DataRow row in dtCheckItems.Rows)
        {
            dto = new EntrustMeteringDTO();
            dto.EntrustMeasurementID = EntrustMeasurementID;
            dto.DetailNo = Convert.ToInt32(seq);
            dto.CheckPointName = row["CheckDesc"].ToString();
            string StrSize = row["StrSize"].ToString();
            if (checktype == "3")
            {
                dto.CheckPointNote = row["StrSize"].ToString();
                dto.DrawingNO = "";
            }
            else
            {
                StrSize = GetCode(dtImage, StrSize);
                dto.CheckPointNote = string.IsNullOrWhiteSpace(StrSize) ? "" : m_CheckPointObj.ConvertTohtml(StrSize, usingImg, isUseIP);
                dto.DrawingNO = string.IsNullOrWhiteSpace(row["DrawingNO"].ToString()) ? "" : row["DrawingNO"].ToString();
            }
            seq += 1;
            if (!m_Entrust.AddAddEntrustMeteringDetailInfo(dto))
            {
                return false;
            }
        }
        return true;
    }

    public String GetCode(DataTable dtImage, string strCode)
    {
        String strHtmlCode, strHtml, strHtmlTemp;
        try
        {
            int i, intStartFlag, intEndFlag;
            strHtml = strCode;
            strHtmlCode = strHtml;
            intStartFlag = strHtmlCode.IndexOf("<img");
            if (intStartFlag == -1)
            {
                intStartFlag = strHtmlCode.IndexOf("<IMG");
            }
            if (intStartFlag > -1)
            {
                intEndFlag = strHtmlCode.IndexOf(">", intStartFlag);
            }
            else
            {
                intEndFlag = -1;
            }

            if (dtImage != null)
            {
                if (dtImage.Rows.Count > 0)
                {
                    while (intStartFlag > -1)
                    {
                        strHtmlTemp = strHtmlCode.Substring(intStartFlag, intEndFlag - intStartFlag + 1);
                        for (i = 0; i <= dtImage.Rows.Count - 1; i++)
                        {
                            if (strHtmlTemp.IndexOf(@"/" + dtImage.Rows[i][0]) > -1)
                            {
                                strHtmlCode = strHtmlCode.Replace(strHtmlTemp, (String)dtImage.Rows[i][1]);
                                break;
                            }

                        }

                        intStartFlag = strHtmlCode.IndexOf("<img", intStartFlag + 1);
                        if (intStartFlag == -1)
                        {
                            intStartFlag = strHtmlCode.IndexOf("<IMG", intStartFlag + 1);
                        }
                        if (intStartFlag > -1)
                        {
                            intEndFlag = strHtmlCode.IndexOf(">", intStartFlag + 1);
                            ;
                        }
                        else
                        {
                            intEndFlag = -1;
                        }
                    }
                }
            }

            return strHtmlCode;
        }
        catch (Exception myError)
        {
            return "";
        }
    }
}